package ktvutil

import (
	"github.com/miekg/dns"
)

var (
	myInternetAddressCache string
)

// 获取互联网的IP地址
// 如果主机没有连接互联网，则返回空
func GetInternetAddress() string {
	target := "myip.opendns.com"
	newip := GetHostAddress(target)
	if len(newip) > 0 {
		myInternetAddressCache = newip
	}

	return newip
}

// 获取缓存的互联网IP地址
func GetInternetCacheAddress() string {
	return myInternetAddressCache
}

func GetHostAddress(target string) string {

	strResult := ""

	// 向opendns的服务器查询myip.opendns.com，即可得到自己的互联网IP地址
	//target := "myip.opendns.com"
	server := "208.67.222.222:5353"

	c := dns.Client{}
	m := dns.Msg{}
	m.SetQuestion(target+".", dns.TypeA)
	r, _, err := c.Exchange(&m, server)
	if err != nil {
		//log.Fatal(err)
		return strResult
	}
	//log.Printf("Took %v", t)
	if len(r.Answer) == 0 {
		return strResult
		//log.Fatal("No results")
	}
	for _, ans := range r.Answer {
		Arecord := ans.(*dns.A)
		//log.Printf("%s", Arecord.A)
		return Arecord.A.String()
	}

	return strResult
}
